package cn.zhentao.controller;

import cn.zhentao.pojo.TUser;
import cn.zhentao.service.UserService;
import cn.zhentao.utils.JwtUtils;
import cn.zhentao.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 小程序登录控制器
 */
@RestController
@RequestMapping("/api/wx/login")
@Api(tags = "小程序登录接口")
@Slf4j
public class WxLoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.secret}")
    private String secret;

    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 小程序登录接口
     * @param code 微信登录临时凭证
     * @return 登录结果（包含token和用户信息）
     */
    @PostMapping
    @ApiOperation(value = "小程序登录", notes = "通过微信小程序code换取用户信息和JWT令牌")
    public Result login(@ApiParam(value = "微信小程序登录凭证", required = true) @RequestParam String code) {
        log.info("小程序登录请求，code: {}", code);
        
        // 参数校验
        if (!StringUtils.hasText(code)) {
            log.warn("登录失败：code参数为空");
            return Result.error("登录凭证不能为空");
        }

        try {
            // 1. 调用微信接口获取openid和session_key
            String url = WX_LOGIN_URL + "?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
            log.info("请求微信API: {}", url.replace(secret, "***"));
            
            Map<String, Object> result = restTemplate.getForObject(url, Map.class);
            log.info("微信API返回结果: {}", result);

            // 检查微信接口返回是否包含错误信息
            if (result == null || result.containsKey("errcode")) {
                String errorMsg = result != null ? (String) result.get("errmsg") : "微信接口调用失败";
                log.error("微信登录失败，错误信息: {}", errorMsg);
                return Result.error("微信登录失败：" + errorMsg);
            }

            String openid = (String) result.get("openid");
            String sessionKey = (String) result.get("session_key");

            if (!StringUtils.hasText(openid)) {
                log.error("微信API返回的openid为空");
                return Result.error("获取用户信息失败");
            }

            log.info("获取到用户openid: {}", openid);

            // 2. 根据openid查询或创建用户
            TUser user = userService.findByOpenid(openid);
            if (user == null) {
                log.info("新用户注册，openid: {}", openid);
                user = new TUser();
                user.setOpenid(openid);
                user.setUserStatus(0); // 正常状态
                user.setCreateTime(new Date());
                user.setUpdateTime(new Date());
                userService.save(user);
                log.info("新用户注册成功，用户ID: {}", user.getId());
            } else {
                log.info("用户已存在，用户ID: {}", user.getId());
                // 更新最后登录时间
                user.setUpdateTime(new Date());
                userService.updateById(user);
            }

            // 3. 生成JWT令牌
            String token = JwtUtils.generateToken(user.getId().toString());
            log.info("为用户生成JWT令牌，用户ID: {}", user.getId());

            // 4. 准备返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("userId", user.getId());
            data.put("openid", user.getOpenid());
            data.put("nickname", user.getNickname());
            data.put("avatarUrl", user.getAvatarUrl());
            data.put("phone", user.getPhone());
            data.put("userStatus", user.getUserStatus());

            log.info("用户登录成功，用户ID: {}", user.getId());
            return Result.success("登录成功", data);
        } catch (Exception e) {
            log.error("登录过程中发生异常", e);
            return Result.error("登录失败，请稍后重试");
        }
    }

    /**
     * 更新用户信息接口
     * @param nickname 用户昵称
     * @param avatarUrl 用户头像
     * @return 更新结果
     */
    @PostMapping("/updateUserInfo")
    @ApiOperation(value = "更新用户信息", notes = "更新用户昵称和头像信息")
    public Result updateUserInfo(@RequestHeader("Authorization") String token,
                                @ApiParam(value = "用户昵称") @RequestParam(required = false) String nickname,
                                @ApiParam(value = "用户头像URL") @RequestParam(required = false) String avatarUrl) {
        log.info("更新用户信息请求，nickname: {}, avatarUrl: {}", nickname, avatarUrl);
        
        try {
            // 验证token
            if (!StringUtils.hasText(token) || !token.startsWith("Bearer ")) {
                return Result.error(401, "请先登录");
            }
            
            String jwtToken = token.substring(7);
            if (!JwtUtils.isValidToken(jwtToken)) {
                return Result.error(401, "登录已过期，请重新登录");
            }
            
            String userId = JwtUtils.getUserIdFromToken(jwtToken);
            TUser user = userService.getById(Long.valueOf(userId));
            
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 更新用户信息
            boolean updated = false;
            if (StringUtils.hasText(nickname)) {
                user.setNickname(nickname);
                updated = true;
            }
            if (StringUtils.hasText(avatarUrl)) {
                user.setAvatarUrl(avatarUrl);
                updated = true;
            }
            
            if (updated) {
                user.setUpdateTime(new Date());
                userService.updateById(user);
                log.info("用户信息更新成功，用户ID: {}", userId);
            }
            
            return Result.success("用户信息更新成功");
        } catch (Exception e) {
            log.error("更新用户信息时发生异常", e);
            return Result.error("更新失败，请稍后重试");
        }
    }

    /**
     * 获取当前用户信息
     * @param token JWT令牌
     * @return 用户信息
     */
    @GetMapping("/userInfo")
    @ApiOperation(value = "获取用户信息", notes = "根据JWT令牌获取当前用户信息")
    public Result getUserInfo(@RequestHeader("Authorization") String token) {
        log.info("获取用户信息请求");
        
        try {
            // 验证token
            if (!StringUtils.hasText(token) || !token.startsWith("Bearer ")) {
                return Result.error(401, "请先登录");
            }
            
            String jwtToken = token.substring(7);
            if (!JwtUtils.isValidToken(jwtToken)) {
                return Result.error(401, "登录已过期，请重新登录");
            }
            
            String userId = JwtUtils.getUserIdFromToken(jwtToken);
            TUser user = userService.getById(Long.valueOf(userId));
            
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("userId", user.getId());
            data.put("openid", user.getOpenid());
            data.put("nickname", user.getNickname());
            data.put("avatarUrl", user.getAvatarUrl());
            data.put("phone", user.getPhone());
            data.put("userStatus", user.getUserStatus());
            data.put("createTime", user.getCreateTime());
            data.put("updateTime", user.getUpdateTime());
            
            log.info("获取用户信息成功，用户ID: {}", userId);
            return Result.success("获取成功", data);
        } catch (Exception e) {
            log.error("获取用户信息时发生异常", e);
            return Result.error("获取失败，请稍后重试");
        }
    }
}
